﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace purchase.Oversell
{
    public class OversellFail
    {
        private static bool IsGoOn = true;//秒杀活动是否结束
        private static int Stock = 0;
        public static void Test()
        {
            Stock = 10;

            for (int i = 0; i < 5000; i++)
            {
                int k = i;
                Task.Run(() =>//每个线程就是一个用户请求
                {
                    if (IsGoOn)
                    {
                        long index = Stock;//-1并且返回 去数据库查一下当前的库存
                        Thread.Sleep(100);

                        if (index >= 1)
                        {
                            Stock = Stock - 1;//更新库存
                            Console.WriteLine($"{k.ToString("000")}秒杀成功，秒杀商品索引为{index}");
                            //可以分队列，去数据库操作
                        }
                        else
                        {
                            if (IsGoOn)
                            {
                                IsGoOn = false;
                            }
                            //Console.WriteLine($"{k.ToString("000")}秒杀失败，秒杀商品索引为{index}");
                        }
                    }
                    else
                    {
                        //Console.WriteLine($"{k.ToString("000")}秒杀停止......");
                    }
                });
            }
            Console.ReadKey();
        }
    }

}
